﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Styx.WoWInternals;
using Styx.Logic.Combat;
using Styx.Helpers;
using System.Drawing;

namespace FelMaster
{
    public class WoWStats
    {
        private ulong spellCasts;
        private Dictionary<WoWSpell, ulong> spellList;
        private DateTime start;

        public void Init()
        {
            Lua.Events.AttachEvent("UNIT_SPELLCAST_START", UNIT_SPELLCAST_START);
            spellCasts = 0;
            spellList = new Dictionary<WoWSpell, ulong>();
            start = DateTime.Now;
        }

        public void Destroy()
        {
            Lua.Events.DetachEvent("UNIT_SPELLCAST_START", UNIT_SPELLCAST_START);
        }

        private void UNIT_SPELLCAST_START(object sender, LuaEventArgs raw)
        {
            var args = raw.Args;
            var player = Convert.ToString(args[0]);

            if (player != "player")
            {
                return;
            }

            //get the english spell name, not the localized one!
            var spellID = Convert.ToInt32(args[4]);
            var spell = WoWSpell.FromId(spellID);

            try
            {
                spellList[spell]++;
            }
            catch
            {
                spellList[spell] = 1;
            }
            spellCasts++;
        }

        private void Log(string str, params object[] a)
        {
            Logging.Write(Color.PeachPuff, str, a);
        }

        public void PrintReport()
        {
            var spells = spellList.OrderByDescending(x => x.Value);
            var seconds = DateTime.Now.Subtract(start).TotalSeconds;
            var minutes = DateTime.Now.Subtract(start).TotalMinutes;

            var apm = (int) ((double)spellCasts / minutes);

            Log("FelMaster stats report:");
            Log("Runtime: {0}minutes", Math.Round(minutes * 10.0) / 10.0);
            Log("Spells cast: {0}", spellCasts > 1000 ? ((Math.Round(spellCasts/100.0)*10)+"k") : spellCasts.ToString());
            Log("Average APM: {0}", apm);
            Log("------------------------------------------");
        }
    }
}
